﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调拨单管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        .container {
            padding: 20px;
        }

        .search-bar {
            margin-bottom: 15px;
            padding: 15px;
            background: #f5f7fa;
            border-radius: 4px;
        }

        .btn-group {
            margin-bottom: 15px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .table-container {
            width: 100%;
            overflow-x: auto;
            margin-bottom: 20px;
        }

        .el-table__fixed-left, .el-table__fixed-right {
            height: auto !important;
            bottom: 0 !important;
            box-shadow: 2px 0 6px rgba(0, 0, 0, 0.08);
        }

        /* 状态样式 */
        .status-draft {
            color: #606266;
        }

        .status-pending {
            color: #e6a23c;
        }

        .status-rejected {
            color: #f56c6c;
        }

        .status-approved {
            color: #409eff;
        }

        .status-completed {
            color: #67c23a;
        }

        .status-outbound-0 {
            color: #606266;
        }

        .status-outbound-1 {
            color: #e6a23c;
        }

        .status-outbound-2 {
            color: #67c23a;
        }

        .status-inbound-0 {
            color: #606266;
        }

        .status-inbound-1 {
            color: #e6a23c;
        }

        .status-inbound-2 {
            color: #67c23a;
        }

        .clickable-order-no {
            color: #409eff;
            cursor: pointer;
            text-decoration: underline;
            transition: color 0.2s;
        }

            .clickable-order-no:hover {
                color: #66b1ff;
            }

        @@media (max-width: 768px) {
            .search-bar .el-form-item {
                width: 100% !important;
                margin-bottom: 10px;
            }

            .btn-group {
                flex-direction: column;
            }

                .btn-group .el-button {
                    width: 100%;
                }
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 加载提示 -->
        <el-loading v-if="loading" fullscreen text="加载中..."></el-loading>

        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form inline :model="searchForm">
                <el-form-item label="调拨单号">
                    <el-input v-model="searchForm.transnoNo" placeholder="请输入" style="width: 200px;" clearable></el-input>
                </el-form-item>
                <el-form-item label="单据状态">
                    <el-select v-model="searchForm.documentStatus" placeholder="请选择" style="width: 150px;" clearable>
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="待审核" value="1"></el-option>
                        <el-option label="驳回" value="2"></el-option>
                        <el-option label="通过" value="3"></el-option>
                        <el-option label="已完成" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="出入库状态">
                    <el-select v-model="searchForm.ioStatus" placeholder="请选择" style="width: 150px;" clearable>
                        <el-option label="未出库" value="out-0"></el-option>
                        <el-option label="部分出库" value="out-1"></el-option>
                        <el-option label="已出库" value="out-2"></el-option>
                        <el-option label="未入库" value="in-0"></el-option>
                        <el-option label="部分入库" value="in-1"></el-option>
                        <el-option label="已入库" value="in-2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="调拨申请日">
                    <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 260px;" clearable></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="default" v-on:click="handleReset">重置</el-button>
                    <el-button type="primary" v-on:click="handleSearch" style="background-color: #00b42a; border-color: #00b42a;">查询</el-button>
                    <!-- 移除高级搜索按钮 -->
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="handleAdd" style="background-color: #00b42a; border-color: #00b42a;">新增</el-button>
            <el-button type="default" v-on:click="handleRefresh">刷新</el-button>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <el-table :data="tableData" border v-on:selection-change="handleSelectionChange"
                      style="width: 100%; min-width: 1200px;"
                      :header-cell-style="{ 'background-color': '#f5f7fa' }"
                      v-loading="tableLoading" element-loading-text="加载中...">
                <!-- 左固定列 -->
                <el-table-column type="selection" width="55" fixed="left"></el-table-column>
                <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>

                <!-- 调拨单号 -->
                <el-table-column label="调拨单号" width="140" fixed="left">
                    <template #default="scope">
                        <span class="clickable-order-no" v-on:click="handleViewDetail(scope.row.transferOrderId)" title="点击查看详情">
                            {{ scope.row.transnoNo || '无单号' }}
                        </span>
                    </template>
                </el-table-column>

                <!-- 单据状态 -->
                <el-table-column label="单据状态" width="110" fixed="left">
                    <template #default="scope">
                        <span :class="getDocumentStatusClass(scope.row.documentStatus)">
                            {{ getDocumentStatusText(scope.row.documentStatus) }}
                        </span>
                    </template>
                </el-table-column>

                <!-- 中间列 -->
                <el-table-column label="调拨申请日期" width="170">
                    <template #default="scope">{{ formatDate(scope.row.tfrrqdt) }}</template>
                </el-table-column>
                <el-table-column prop="transferType" label="调拨类型" width="130">
                    <template #default="scope">{{ scope.row.transferType || '-' }}</template>
                </el-table-column>
                <el-table-column prop="outWarehouseName" label="调出仓库" width="130">
                    <template #default="scope">{{ scope.row.outWarehouseName || '-' }}</template>
                </el-table-column>
                <el-table-column prop="inWarehouseName" label="调入仓库" width="130">
                    <template #default="scope">{{ scope.row.inWarehouseName || '-' }}</template>
                </el-table-column>

                <!-- 出库状态 -->
                <el-table-column label="出库状态" width="110">
                    <template #default="scope">
                        <span :class="getOutboundStatusClass(scope.row.outboundStatus)">
                            {{ getOutboundStatusText(scope.row.outboundStatus) }}
                        </span>
                    </template>
                </el-table-column>

                <!-- 入库状态 -->
                <el-table-column label="入库状态" width="110">
                    <template #default="scope">
                        <span :class="getInboundStatusClass(scope.row.storageStatus)">
                            {{ getInboundStatusText(scope.row.storageStatus) }}
                        </span>
                    </template>
                </el-table-column>

                <!-- 调拨数量 -->
                <el-table-column label="调拨数量" width="110" align="right">
                    <template #default="scope">
                        {{ scope.row.transferQuantity > 0 ? scope.row.transferQuantity : '0' }}
                    </template>
                </el-table-column>

                <!-- 调拨金额 -->
                <el-table-column label="调拨金额" width="120" align="right">
                    <template #default="scope">
                        {{ (scope.row.transferAmount > 0 ? scope.row.transferAmount : 0).toFixed(2) }}
                    </template>
                </el-table-column>

                <el-table-column prop="handlerName" label="经办人" width="110">
                    <template #default="scope">{{ scope.row.handlerName || '-' }}</template>
                </el-table-column>

                <!-- 调拨货品 -->
                <el-table-column label="调拨货品" width="200">
                    <template #default="scope">
                        <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" :title="scope.row.productName">
                            {{ scope.row.productName || '无货品' }}
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="makerName" label="制单人" width="110">
                    <template #default="scope">{{ scope.row.makerName || '-' }}</template>
                </el-table-column>
                <el-table-column prop="departmentName" label="所在部门" width="130">
                    <template #default="scope">{{ scope.row.departmentName || '-' }}</template>
                </el-table-column>
                <el-table-column label="制单时间" width="170">
                    <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
                </el-table-column>
                <el-table-column prop="reviewerName" label="审核人" width="110">
                    <template #default="scope">{{ scope.row.reviewerName || '-' }}</template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" width="320" fixed="right">
                    <template #default="scope">
                        <!-- 删除按钮：所有状态强制显示 -->
                        <el-button type="text" size="small" style="color: #f56c6c;"
                                   v-on:click="handleDelete(scope.row.transferOrderId)">删除</el-button>

                        <!-- 待审核状态显示通过/驳回按钮 -->
                        <template v-if="scope.row.documentStatus === '1'">
                            <el-button type="text" size="small" style="color: #409eff;"
                                       v-on:click="handleSingleAudit(scope.row.transferOrderId, true)">通过</el-button>
                            <el-button type="text" size="small" style="color: #f56c6c;"
                                       v-on:click="handleSingleAudit(scope.row.transferOrderId, false)">驳回</el-button>
                        </template>

                        <!-- 草稿和驳回状态显示编辑按钮 -->
                        <template v-if="scope.row.documentStatus === '0' || scope.row.documentStatus === '2'">
                            <el-button type="text" size="small" v-on:click="handleEdit(scope.row.transferOrderId)">编辑</el-button>
                        </template>

                        <!-- 已审核/已完成显示撤销按钮 -->
                        <template v-if="scope.row.documentStatus === '3' || scope.row.documentStatus === '4'">
                            <el-button type="text" size="small" style="color: #e6a23c;"
                                       v-on:click="handleCancel(scope.row.transferOrderId)">撤销</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <el-pagination v-on:size-change="handleSizeChange" v-on:current-change="handleCurrentChange"
                       :current-page="pagination.pageNum" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
                       layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                       style="margin-top: 15px; text-align: right;">
        </el-pagination>
    </div>

    <script>
        const { ref, reactive, onMounted } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        const app = Vue.createApp({
            setup() {
                // 搜索表单
                const searchForm = reactive({
                    transnoNo: '',
                    documentStatus: '',
                    ioStatus: '',
                    dateRange: []
                });

                // 表格数据
                const tableData = ref([]);
                const pagination = reactive({ pageNum: 1, pageSize: 10, total: 0 });
                const selectedIds = ref([]);
                const loading = ref(false);
                const tableLoading = ref(false);

                // 初始化加载
                onMounted(() => handleSearch());

                // 日期格式化
                const formatDate = (dateStr) => {
                    if (!dateStr) return '-';
                    try {
                        let timestamp;
                        if (typeof dateStr === 'string' && dateStr.startsWith('/Date(') && dateStr.endsWith(')/')) {
                            timestamp = parseInt(dateStr.slice(6, -2));
                        } else {
                            timestamp = new Date(dateStr).getTime();
                        }
                        if (isNaN(timestamp)) return dateStr || '-';
                        const date = new Date(timestamp);
                        return date.toLocaleString('zh-CN', {
                            year: 'numeric', month: '2-digit', day: '2-digit',
                            hour: '2-digit', minute: '2-digit', second: '2-digit'
                        }).replace(/\//g, '-');
                    } catch (e) {
                        console.error('日期格式化失败：', e);
                        return dateStr || '-';
                    }
                };

                // 单据状态转换
                const getDocumentStatusText = (status) => {
                    if (!status) return '-';
                    const map = { '0': '草稿', '1': '待审核', '2': '驳回', '3': '通过', '4': '已完成' };
                    return map[status] || `未知(${status})`;
                };

                // 单据状态样式
                const getDocumentStatusClass = (status) => {
                    const text = getDocumentStatusText(status);
                    const map = { '草稿': 'status-draft', '待审核': 'status-pending', '驳回': 'status-rejected', '通过': 'status-approved', '已完成': 'status-completed' };
                    return map[text] || '';
                };

                // 出库状态转换
                const getOutboundStatusText = (status) => {
                    if (!status) return '-';
                    const map = { '0': '未出库', '1': '部分出库', '2': '已出库' };
                    return map[status] || `未知(${status})`;
                };

                // 入库状态转换
                const getInboundStatusText = (status) => {
                    if (!status) return '-';
                    const map = { '0': '未入库', '1': '部分入库', '2': '已入库' };
                    return map[status] || `未知(${status})`;
                };

                // 出库状态样式
                const getOutboundStatusClass = (status) => {
                    const map = { '0': 'status-outbound-0', '1': 'status-outbound-1', '2': 'status-outbound-2' };
                    return map[status] || '';
                };

                // 入库状态样式
                const getInboundStatusClass = (status) => {
                    const map = { '0': 'status-inbound-0', '1': 'status-inbound-1', '2': 'status-inbound-2' };
                    return map[status] || '';
                };

                // 查看详情
                const handleViewDetail = (id) => {
                    window.location.href = `/TransferOrder/Detail?id=${id}`;
                };

                // 获取数据 - 修复出入库状态查询逻辑
                const fetchData = async () => {
                    tableLoading.value = true;
                    try {
                        let ioType = '';
                        let ioStatus = '';

                        // 修复出入库状态参数处理
                        if (searchForm.ioStatus) {
                            const parts = searchForm.ioStatus.split('-');
                            if (parts.length === 2) {
                                ioType = parts[0]; // 'out' 或 'in'
                                ioStatus = parts[1]; // '0', '1', '2'
                            }
                        }

                        const params = {
                            transnoNo: searchForm.transnoNo,
                            documentStatus: searchForm.documentStatus,
                            ioType: ioType,
                            ioStatus: ioStatus,
                            startDate: searchForm.dateRange?.[0] ? new Date(searchForm.dateRange[0]).toISOString().split('T')[0] : '',
                            endDate: searchForm.dateRange?.[1] ? new Date(searchForm.dateRange[1]).toISOString().split('T')[0] : '',
                            pageIndex: pagination.pageNum,
                            pageSize: pagination.pageSize
                        };

                        console.log('查询参数：', params);

                        const response = await axios.post('/TransferOrder/GetTransferOrders', params);
                        console.log('后端返回数据：', response.data);

                        if (response.data.error) {
                            ElMessage.error(response.data.error);
                            return;
                        }

                        tableData.value = response.data.data || [];
                        pagination.total = response.data.total || 0;
                    } catch (error) {
                        console.error('数据加载失败：', error);
                        ElMessage.error('数据加载失败：' + error.message);
                    } finally {
                        tableLoading.value = false;
                    }
                };

                // 搜索/重置
                const handleSearch = () => {
                    pagination.pageNum = 1;
                    fetchData();
                };

                const handleReset = () => {
                    searchForm.transnoNo = '';
                    searchForm.documentStatus = '';
                    searchForm.ioStatus = '';
                    searchForm.dateRange = [];
                    pagination.pageNum = 1;
                    fetchData();
                };

                // 新增/编辑/删除
                const handleAdd = () => {
                    window.location.href = '/TransferOrder/Add';
                };

                const handleEdit = (id) => window.location.href = `/TransferOrder/Edit?transferOrderId=${id}`;

                const handleDelete = async (id) => {
                    let statusText = getDocumentStatusText(tableData.value.find(item => item.transferOrderId === id)?.documentStatus);
                    let confirmMessage = `确定删除该${statusText}状态的调拨单？删除后不可恢复！`;

                    if (['通过', '已完成'].includes(statusText)) {
                        confirmMessage += '\n此操作可能影响库存数据，请谨慎操作！';
                    }

                    ElMessageBox.confirm(
                        confirmMessage,
                        '确认删除',
                        { type: 'danger' }
                    ).then(async () => {
                        try {
                            const res = await axios.post('/TransferOrder/Delete', { transferOrderId: id });
                            if (res.data.success) {
                                ElMessage.success('删除成功');
                                fetchData();
                            } else {
                                ElMessage.error(res.data.message || '删除失败');
                            }
                        } catch (e) {
                            ElMessage.error('删除失败：' + e.message);
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                };

                // 单条审核功能
                const handleSingleAudit = async (transferOrderId, isPass) => {
                    try {
                        const auditResult = isPass ? '3' : '2';
                        const res = await axios.post('/TransferOrder/Audit', {
                            ids: [transferOrderId],
                            auditResult: auditResult
                        });

                        if (res.data.successIds && res.data.successIds.length > 0) {
                            ElMessage.success({
                                message: `${isPass ? '审核通过' : '审核驳回'}成功：ID=${res.data.successIds.join(',')}`,
                                duration: 5000
                            });
                        }

                        if (res.data.failIds && Object.keys(res.data.failIds).length > 0) {
                            let failMsg = `${isPass ? '审核通过' : '审核驳回'}失败：\n`;
                            Object.entries(res.data.failIds).forEach(([id, msg]) => {
                                failMsg += `ID=${id}：${msg}\n`;
                            });
                            ElMessage.error({
                                message: failMsg.trim(),
                                duration: 8000
                            });
                        }

                        fetchData();
                    } catch (e) {
                        ElMessage.error(`操作失败：${e.message}`);
                    }
                };

                // 导出功能
                const handleExport = () => {
                    let ioType = '';
                    let ioStatus = '';
                    if (searchForm.ioStatus) {
                        const [type, status] = searchForm.ioStatus.split('-');
                        ioType = type;
                        ioStatus = status;
                    }

                    const params = new URLSearchParams();
                    params.append('transnoNo', searchForm.transnoNo);
                    params.append('documentStatus', searchForm.documentStatus);
                    params.append('ioType', ioType);
                    params.append('ioStatus', ioStatus);
                    if (searchForm.dateRange?.[0]) params.append('startDate', new Date(searchForm.dateRange[0]).toISOString().split('T')[0]);
                    if (searchForm.dateRange?.[1]) params.append('endDate', new Date(searchForm.dateRange[1]).toISOString().split('T')[0]);
                    window.open(`/TransferOrder/Export?${params.toString()}`, '_blank');
                };

                // 刷新功能
                const handleRefresh = () => fetchData();

                // 撤销功能
                const handleCancel = async (transferOrderId) => {
                    console.log('传递的调拨单ID：', transferOrderId);
                    if (!transferOrderId || transferOrderId <= 0) {
                        ElMessage.warning('调拨单ID无效（必须为正数）');
                        return;
                    }

                    ElMessageBox.confirm(
                        '确定要撤销该调拨单吗？\n已审核通过的单据将自动回滚库存！',
                        '撤销确认',
                        {
                            confirmButtonText: '确认撤销',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(async () => {
                        try {
                            const response = await axios.post('/TransferOrder/Cancel', {
                                id: transferOrderId
                            });

                            if (response.data.success) {
                                ElMessage.success('撤销成功！已重置为待审核状态');
                                fetchData();
                            } else {
                                ElMessage.error(`撤销失败：${response.data.message}`);
                            }
                        } catch (error) {
                            console.error('撤销请求异常：', error);
                            ElMessage.error(`网络异常：${error.message}`);
                        }
                    }).catch(() => {
                        ElMessage.info('已取消撤销操作');
                    });
                };

                // 选择/分页
                const handleSelectionChange = (selection) => {
                    selectedIds.value = selection.map(item => item.transferOrderId);
                };

                const handleSizeChange = (size) => {
                    pagination.pageSize = size;
                    pagination.pageNum = 1;
                    fetchData();
                };

                const handleCurrentChange = (page) => {
                    pagination.pageNum = page;
                    fetchData();
                };

                return {
                    searchForm, tableData, pagination, selectedIds, loading, tableLoading,
                    formatDate, getDocumentStatusText, getDocumentStatusClass,
                    getOutboundStatusText, getInboundStatusText,
                    getOutboundStatusClass, getInboundStatusClass,
                    handleViewDetail, handleSearch, handleReset,
                    handleAdd, handleEdit, handleDelete,
                    handleRefresh, handleCancel, handleSingleAudit,
                    handleSelectionChange, handleSizeChange, handleCurrentChange
                };
            }
        });

        app.use(ElementPlus).mount('#app');
    </script>
</body>
</html>